package com.ilink.groundservice.controller.AiXNew;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ilink.groundservice.entity.VO.AiX.AiXPracticeProjectResponse;
import com.ilink.groundservice.entity.VO.AiX.AiXPracticeRecordResponse;
import com.ilink.groundservice.service.Practice.AiXPracticeProjectService;
import com.ilink.groundservice.service.Practice.AiXPracticeRecordService;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPracticeProjectFilterRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPracticeProjectInsertRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPracticeProjectUpdateRequest;
import com.ilink.ilinkapi.dto.ground.AiX.AiXPracticeRecordRequest;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/ground/aix/practice")
@RestController
@RequiredArgsConstructor
public class AiXPracticeController {

    private final AiXPracticeProjectService practiceProjectService;
    private final AiXPracticeRecordService practiceRecordService;

    @MethodLog("获取实训项目列表")
    @GetMapping("/projects")
    public R getPracticeProjects(@RequestParam(required = false) Long areaId,
                                 @RequestParam(required = false) String tag,
                                 @RequestParam(required = false) String keyword,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer size) {
        try {
            AiXPracticeProjectFilterRequest request = new AiXPracticeProjectFilterRequest();
            request.setAreaId(areaId);
            request.setTag(tag);
            request.setKeyword(keyword);
            request.setPage(page);
            request.setSize(size);
            
            IPage<AiXPracticeProjectResponse> responseIPage = practiceProjectService.getPracticeProjectList(request);
            log.info("获取实训项目列表成功, total: {}", responseIPage.getTotal());
            return R.ok("实训项目列表获取成功", responseIPage);
        } catch (Exception e) {
            log.error("获取实训项目列表失败: {}", e.getMessage());
            return R.error("获取实训项目列表失败: " + e.getMessage());
        }
    }

    @MethodLog("获取实训项目详情")
    @GetMapping("/projects/{projectId}")
    public R getPracticeProjectDetail(@PathVariable Long projectId) {
        try {
            AiXPracticeProjectResponse response = practiceProjectService.getPracticeProjectById(projectId);
            log.info("获取实训项目详情成功, projectId: {}", projectId);
            return R.ok("实训项目详情获取成功", response);
        } catch (Exception e) {
            log.error("获取实训项目详情失败: {}", e.getMessage());
            return R.error("获取实训项目详情失败: " + e.getMessage());
        }
    }

    @MethodLog("开始实训项目")
    @PostMapping("/projects/{projectId}/start")
    public R startPracticeProject(@PathVariable Long projectId) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            Long recordId = practiceRecordService.startPracticeProject(projectId, userId);
            log.info("开始实训项目成功, projectId: {}, userId: {}, recordId: {}", projectId, userId, recordId);
            return R.ok("实训项目开始成功", recordId);
        } catch (Exception e) {
            log.error("开始实训项目失败: {}", e.getMessage());
            return R.error("开始实训项目失败: " + e.getMessage());
        }
    }

    @MethodLog("提交实训作业")
    @PostMapping("/projects/{projectId}/submit")
    public R submitPracticeWork(@PathVariable Long projectId,
                                @RequestParam(required = false) MultipartFile file,
                                @RequestParam(required = false) String notes) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            practiceRecordService.submitPracticeWork(projectId, userId, notes);
            log.info("提交实训作业成功, projectId: {}, userId: {}, notes: {}", projectId, userId, notes);
            return R.ok("实训作业提交成功");
        } catch (Exception e) {
            log.error("提交实训作业失败: {}", e.getMessage());
            return R.error("提交实训作业失败: " + e.getMessage());
        }
    }

    @MethodLog("获取实训记录")
    @GetMapping("/records")
    public R getPracticeRecords(@RequestParam(required = false) String status,
                                @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "10") Integer size) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            IPage<AiXPracticeRecordResponse> responseIPage = practiceRecordService.getUserPracticeRecords(userId, status, page, size);
            log.info("获取实训记录成功, userId: {}, status: {}, total: {}", userId, status, responseIPage.getTotal());
            return R.ok("实训记录获取成功", responseIPage);
        } catch (Exception e) {
            log.error("获取实训记录失败: {}", e.getMessage());
            return R.error("获取实训记录失败: " + e.getMessage());
        }
    }

    @MethodLog("获取实训统计信息")
    @GetMapping("/statistics")
    public R getPracticeStatistics() {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            Map<String, Object> statistics = practiceRecordService.getUserPracticeStatistics(userId);
            log.info("获取实训统计信息成功, userId: {}", userId);
            return R.ok("实训统计信息获取成功", statistics);
        } catch (Exception e) {
            log.error("获取实训统计信息失败: {}", e.getMessage());
            return R.error("获取实训统计信息失败: " + e.getMessage());
        }
    }

    @MethodLog("结束实训项目")
    @PostMapping("/projects/{projectId}/end")
    public R endPracticeProject(@PathVariable Long projectId,
                                @RequestParam(required = false) Integer score) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            practiceRecordService.endPracticeProject(projectId, userId, score);
            log.info("结束实训项目成功, projectId: {}, userId: {}, score: {}", projectId, userId, score);
            return R.ok("实训项目结束成功");
        } catch (Exception e) {
            log.error("结束实训项目失败: {}", e.getMessage());
            return R.error("结束实训项目失败: " + e.getMessage());
        }
    }

    // 管理员接口：创建实践项目
    @MethodLog("创建实践项目")
    @PostMapping("/projects/create")
    public R createPracticeProject(AiXPracticeProjectInsertRequest request) {
        try {
            Long projectId = practiceProjectService.insertPracticeProject(request);
            log.info("创建实践项目成功, projectId: {}", projectId);
            return R.ok("实践项目创建成功", projectId);
        } catch (Exception e) {
            log.error("创建实践项目失败: {}", e.getMessage());
            return R.error("创建实践项目失败: " + e.getMessage());
        }
    }

    // 管理员接口：更新实践项目
    @MethodLog("更新实践项目")
    @PostMapping("/projects/update")
    public R updatePracticeProject(@RequestBody AiXPracticeProjectUpdateRequest request) {
        try {
            practiceProjectService.updatePracticeProject(request);
            log.info("更新实践项目成功, projectId: {}", request.getProjectId());
            return R.ok("实践项目更新成功");
        } catch (Exception e) {
            log.error("更新实践项目失败: {}", e.getMessage());
            return R.error("更新实践项目失败: " + e.getMessage());
        }
    }

    // 管理员接口：删除实践项目
    @MethodLog("删除实践项目")
    @PostMapping("/projects/delete/{projectId}")
    public R deletePracticeProject(@PathVariable Long projectId) {
        try {
            practiceProjectService.deletePracticeProject(projectId);
            log.info("删除实践项目成功, projectId: {}", projectId);
            return R.ok("实践项目删除成功");
        } catch (Exception e) {
            log.error("删除实践项目失败: {}", e.getMessage());
            return R.error("删除实践项目删除失败: " + e.getMessage());
        }
    }

    // 管理员接口：更新实践项目封面
    @MethodLog("更新实践项目封面")
    @PostMapping("/projects/{projectId}/cover")
    public R updatePracticeProjectCover(@PathVariable Long projectId,
                                        @RequestParam("file") MultipartFile file) {
        try {
            practiceProjectService.updatePracticeProjectCover(file, projectId);
            log.info("更新实践项目封面成功, projectId: {}", projectId);
            return R.ok("实践项目封面更新成功");
        } catch (Exception e) {
            log.error("更新实践项目封面失败: {}", e.getMessage());
            return R.error("更新实践项目封面失败: " + e.getMessage());
        }
    }

    @MethodLog("获取热门实践项目")
    @GetMapping("/projects/popular")
    public R getPopularPracticeProjects(@RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<AiXPracticeProjectResponse> projects = practiceProjectService.getPopularPracticeProjects(limit);
            log.info("获取热门实践项目成功, count: {}", projects.size());
            return R.ok("热门实践项目获取成功", projects);
        } catch (Exception e) {
            log.error("获取热门实践项目失败: {}", e.getMessage());
            return R.error("获取热门实践项目失败: " + e.getMessage());
        }
    }

    @MethodLog("更新实践记录")
    @PostMapping("/records/update")
    public R updatePracticeRecord(@RequestBody AiXPracticeRecordRequest request) {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            practiceRecordService.updatePracticeRecord(request, userId);
            log.info("更新实践记录成功, userId: {}, projectId: {}", userId, request.getProjectId());
            return R.ok("实践记录更新成功");
        } catch (Exception e) {
            log.error("更新实践记录失败: {}", e.getMessage());
            return R.error("更新实践记录失败: " + e.getMessage());
        }
    }

    @MethodLog("获取实训项目最常用的8个标签")
    @GetMapping("/get_practice_project_tags")
    public R getPracticeProjectTags(@RequestParam Long areaId) {
        try {
            List<String> tags = practiceProjectService.getPracticeProjectTags(areaId);
            return R.ok("实训项目最常用的8个标签", tags);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("获取实训项目标签")
    @GetMapping("/categories/tags")
    public R getAllPracticeProjectTags(@RequestParam Long areaId) {
        try {
            List<String> tags = practiceProjectService.getAllPracticeProjectTags(areaId);
            log.info("获取实训项目标签成功, count: {}", tags.size());
            return R.ok("实训项目标签获取成功", tags);
        } catch (Exception e) {
            log.error("获取实训项目标签失败: {}", e.getMessage());
            return R.error("获取实训项目标签失败: " + e.getMessage());
        }
    }

    @MethodLog("获取用户已完成的实践项目")
    @GetMapping("/records/completed")
    public R getCompletedPracticeRecords() {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            List<AiXPracticeRecordResponse> records = practiceRecordService.getCompletedPracticeRecords(userId);
            log.info("获取用户已完成的实践项目成功, userId: {}, count: {}", userId, records.size());
            return R.ok("已完成实践项目获取成功", records);
        } catch (Exception e) {
            log.error("获取用户已完成的实践项目失败: {}", e.getMessage());
            return R.error("获取用户已完成的实践项目失败: " + e.getMessage());
        }
    }

    @MethodLog("获取用户正在进行的实践项目")
    @GetMapping("/records/in-progress")
    public R getInProgressPracticeRecords() {
        try {
            String userId = UserContext.getUserId();
            if (userId == null) {
                return R.error("用户未登录");
            }
            
            List<AiXPracticeRecordResponse> records = practiceRecordService.getInProgressPracticeRecords(userId);
            log.info("获取用户正在进行的实践项目成功, userId: {}, count: {}", userId, records.size());
            return R.ok("正在进行实践项目获取成功", records);
        } catch (Exception e) {
            log.error("获取用户正在进行的实践项目失败: {}", e.getMessage());
            return R.error("获取用户正在进行的实践项目失败: " + e.getMessage());
        }
    }
} 